package com.easychat.mychat.common.Aspect;


import com.easychat.mychat.common.Redis.RedisUtils;
import com.easychat.mychat.common.annotation.GlobalInteceptor;
import com.easychat.mychat.common.entity.constants.Constants;
import com.easychat.mychat.common.entity.dto.TokenUserInfoDto;
import com.easychat.mychat.common.entity.enums.ResponseCodeEnum;
import com.easychat.mychat.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Description
 * @Author susu
 * @Date 2024/9/5
 */
@Aspect
@Component
@Slf4j
public class validateAspect {

    @Resource
    private RedisUtils redisUtils;

    @Pointcut("@annotation(com.example.mychat.annotation.GlobalInteceptor)")
    private void poincut(){}


    @Before("poincut()")
    private void validate(JoinPoint point) throws NoSuchMethodException {
        String name = point.getSignature().getName();
        Class[] parameterTypes = ((MethodSignature) point.getSignature()).getParameterTypes();
        Method method = point.getTarget().getClass().getMethod(name, parameterTypes);
        GlobalInteceptor annotation = method.getAnnotation(GlobalInteceptor.class);

        try {
            if (annotation.checkLogin() || annotation.checkAdmin()) {
                checkLogin(annotation.checkAdmin());
            }
        }catch (BusinessException e){
            log.error("全局拦截异常",e);
            throw e;
        }catch (Exception e){
            log.error("全局拦截异常",e);
            throw new BusinessException(ResponseCodeEnum.CODE_500);
        }
    }
    private void checkLogin(Boolean checkAdmin){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        TokenUserInfoDto o =(TokenUserInfoDto) redisUtils.get(Constants.REDIS_KEY_WS_TOKEN + token);
        if (o == null){
            throw new BusinessException(ResponseCodeEnum.CODE_901);
        }
        String a =(String) redisUtils.get(Constants.REDIS_KEY_WS_TOKEN_USERID + o.getUserId());
        if (!a.equals(token)){
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        if (checkAdmin && !o.getAdmin()) {
            throw new BusinessException(ResponseCodeEnum.CODE_404);
        }
    }
}
